package com.hotel.service.impl;

import com.hotel.bean.Employee;
import com.hotel.exception.SteduException;
import com.hotel.mapper.EmployeeMapper;
import com.hotel.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @CacheEvict(value = "hotel_system",key = "'EmployeeList'")
    @Override
    public boolean insert(Employee employee) {
        return employeeMapper.insert(employee) == 1;
    }
    @Caching(
            evict = {
                    @CacheEvict(value = "hotel_system",key = "'EmployeeList'"),
                    @CacheEvict(value = "hotel_system",key = "#eid")
            }
    )
    @Override
    public boolean deleteByEid(Integer eid) throws SteduException {
        if(employeeMapper.selectByEid(eid) == null){
            throw new SteduException("编号不存在");
        }
        return employeeMapper.deleteByEid(eid) == 1;
    }
    @Caching(
            evict = {
                    @CacheEvict(value = "hotel_system",key = "'EmployeeList'"),
                    @CacheEvict(value = "hotel_system",key = "#employee.eid")
            }
    )
    @Override
    public boolean update(Employee employee) {
        return employeeMapper.update(employee) == 1;
    }
    @Cacheable(value ="hotel_system",key = "#eid")
    @Override
    public Employee selectByEid(Integer eid) throws SteduException {
        if(employeeMapper.selectByEid(eid) == null){
            throw new SteduException("编号不存在");
        }
        return employeeMapper.selectByEid(eid);
    }
    @Cacheable(value = "hotel_system" ,key = "'EmployeeList'",unless = "#result == null || #result.size() == 0")
    @Override
    public List<Employee> selectAll(String ename) {
        return employeeMapper.selectAll(ename);
    }
    @Cacheable(value ="hotel_system",key = "#eid",unless = "#result==null")
    @Override
    public List<Integer> selectDidByEid(Integer eid) {
        return employeeMapper.selectDidByEid(eid);
    }
    @Caching(
            evict = {
                    @CacheEvict(value = "hotel_system",key = "'EmployeeList'"),
                    @CacheEvict(value = "hotel_system",key = "#eid")
            }
    )
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertEidAndDid(Integer eid, Integer[] dids) throws SteduException {
        if( dids.length == 0){
            throw new SteduException("添加失败，员工至少有一个部门");
        }
        employeeMapper.deleteEidAndDidByEid(eid);
        employeeMapper.insertEidAndDid(eid,dids);
    }
}
